package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.AuthFeignService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserReq;
import com.bwie.common.domain.response.JwtRes;
import com.bwie.common.redis.service.RedisService;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: AuthServiceImpl
 * @Description:
 * @Author: ZengFz
 * @Date: 2024/5/17 9:32:02
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthFeignService authFeignService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<JwtRes> login(UserReq userReq) {
        //模拟微信登录，用户输入参数为手机号 和 openid
        if (StringUtils.isAnyBlank(userReq.getTel(),userReq.getCode())){
            throw new RuntimeException("手机号或openid不能为空");
        }
        //远程调用
        User user = authFeignService.findUserByTel(userReq.getTel()).getData();
        if (user == null){
            throw new RuntimeException("用户不存在，请先注册");
        }
        //openid(这个一个固定值就可)
        String openid = "1234";
        if (!openid.equals(userReq.getCode())){
            throw new RuntimeException("openid错误，请重新输入");
        }
        //验证 成功 ===》 登录
        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        //基于token令牌完成登录认证，token使用JWT生成
        String token = JwtUtils.createToken(map);

        redisService.setCacheObject(TokenConstants.LOGIN_TOKEN_KEY+userKey, user,30L, TimeUnit.MINUTES);

        JwtRes jwtRes = new JwtRes();
        jwtRes.setToken(token);
        jwtRes.setExpireTimeStr("30分钟");

        return Result.success(jwtRes);
    }

    @Override
    public User info() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        Object userJson = redisService.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return (User) userJson;
    }

    @Override
    public void logout() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisService.deleteObject(TokenConstants.LOGIN_TOKEN_KEY+userKey);
    }


}
